﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;

namespace ConfigDatabase
{
    public partial class FormSetupDatabase : Form
    {
        public FormSetupDatabase()
        {
            InitializeComponent();
        }

        private static void RunScript(string script, string connectionString)
        {
            //string script = File.ReadAllText(fileName);
            var conn = new SqlConnection(connectionString);
            var comm = new SqlCommand(string.Empty, conn);
            conn.Open();

            string[] commands = script.Split(new[] {Environment.NewLine + "GO" + Environment.NewLine},
                                             StringSplitOptions.RemoveEmptyEntries);

            foreach (string command in commands)
            {
                comm.CommandText = command;
                comm.ExecuteNonQuery();
            }

            conn.Close();
        }

        private static string CreateConnection(string serverName, string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return string.Format("Data Source={0};Integrated Security=True;", serverName);
            }

            return string.Format("Data Source={0};User Id={1};Password={2};", serverName, username, password);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog {Filter = "Sql Files (.sql)|*.sql"};

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = dialog.FileName;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                string script = File.Exists(txtPath.Text) ? File.ReadAllText(txtPath.Text) : Script.DatabaseScript;
                string conectionString = CreateConnection(
                    txtServerName.Text, txtServerUsername.Text, txtServerPassword.Text);

                RunScript(script, conectionString);

                MessageBox.Show("Done!");
                Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}